--#!/usr/bin/env lua
--[[

检查是否登录，如果登录则提取用户的信息，将用户信息放在ngx.req.ctx.userinfo中

]]

----local logger=logger;
local CheckLoginFilter = Class("com.ea.filter.CheckLoginFilter")

local cjson = require "cjson"
local utils = require "com.ea.util.utils"
local oriRedis = require "resty.redis"
local userinfo = require("com.ea.vo.UserInfo")
local userType={buyer=3,seller=2,unkown=1}


function CheckLoginFilter:init()
  if ngx.var.APP_DEBUG_LOG== "true" then ngx.log(ngx.DEBUG,logger.formatMsg(" in init")) end
  self.beanFactory = luastar_context.getBeanFactory();
end

--[[
从请求头或者参数中获取token，如果没有则返回nil
]]

function CheckLoginFilter:getToken()
  local token=nil
  token=ngx.req.get_headers()["token"]
  if not token then
    local last_req_args = utils:get_req_args_all();
    token = utils:get_req_param("token",last_req_args);
  end
  if not token then 
      return nil 
  else  
      return token 
  end
  if ngx.var.APP_DEBUG_LOG== "true" then ngx.log(ngx.DEBUG,logger.formatMsg(string.format("token = %s",token))); end
end
--[[
  若成功获取到用户信息，则返回UserInfo对象，否则返回nil,异常为nil.
  如果出现redis请求/参数等异常，则返回nil,异常不为nil
]]
function CheckLoginFilter:getUserInfoFromRedis(request,response)

  local token = self:getToken();
  if not token then 
     return nil,nil
  end
     

     local redis_bean = self.beanFactory:getBean("bean_redis_portal")
     local r=oriRedis:new();--使用OR的原生redis客户端来将array_to_hash。

    local res,err = redis_bean:hgetall(token)  
    if _.isEmpty(res)==false then
       local var_userinfo = userinfo:new()
       local h = r:array_to_hash(res);
        var_userinfo:setPhone(h.phone);
        var_userinfo:setUserId ( h.userId)
        var_userinfo:setNickName(h.nickName)
        var_userinfo:setUserLogo(h.userLogo)        
        var_userinfo:setLoginStatus(true)
        var_userinfo:setCityId(h.cityId);
        --token是以cp开头的是buyer
        local _startIndex,_endIndex=string.find(token,"cp:");
        if _starIndex==1 and _endIndex==3 then
          var_userinfo:setUserType(userType.buyer)        
        end;
        --p:开头的token是微店系统产生的，当前用户是微店用户
         _starIndex,_endIndex=string.find(token,"p:");
        if  _starIndex==1 and _endIndex==2 then
          var_userinfo:setUserType(userType.seller) 
          var_userinfo:setShopId(h.shopId)
          var_userinfo:setShopName(h.shopName)
        end 
        _starIndex,_endIndex=string.find(token,"py:");
        if  _starIndex==1 and _endIndex==2 then
          var_userinfo:setUserType(userType.seller) 
          var_userinfo:setShopId(h.shopId)
          var_userinfo:setShopName(h.shopName)
        end                 
        return var_userinfo,nil
    else
        if ngx.var.APP_DEBUG_LOG== "true" then ngx.log(ngx.DEBUG,logger.formatMsg(" read data from redis is empty ,return is  ",err)) end
        return nil,err
    end
  
end
--[[

检查用户信息

]]
function CheckLoginFilter:doFilter(request,response)
   -- require('mobdebug').start('172.29.58.73')
    local appConfig=luastar_context.loadJsonConfig("config");
    local URLNeedLogin=false;
    local _str=string.sub(ngx.var.uri,-3,-1)
    local wholeUrl=ngx.var.uri
    if _str==".do" then
        wholeUrl=string.sub(ngx.var.uri,1,-4)
    end 
    for i,v in pairs (appConfig.need_login) do
        if wholeUrl==v then
          if ngx.var.APP_DEBUG_LOG== "true" then ngx.log(ngx.DEBUG,logger.formatMsg(string.format("%s needlogind",wholeUrl))); end
          URLNeedLogin=true;
          break;
        end
         --if ngx.var.APP_DEBUG_LOG== "true" then ngx.log(ngx.DEBUG,logger.formatMsg(string.format(" need_login uri %s %s",i,v))); end
    end
    local var_userinfo ,err = self:getUserInfoFromRedis(request,response);
    if _.isEmpty(var_userinfo)  and URLNeedLogin==true then---URL地址需要登录，则阻止用户后续操作
          response:responseJson(cjson.encode({state=3829201,msg="用户未登录,请登录",data=nil}))
          ngx.log(ngx.INFO,logger.formatMsg(string.format("用户未登录，需要登录才能访问。URI:%s",ngx.var.uri)));
         return false
    end  
  request:setAttribute("userinfo",var_userinfo)
  --require('mobdebug').done();
  return true
end

return CheckLoginFilter;

        

     
     
 
 